package dmsxl.haxibiao;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Author: Zhang Dongwei
 * Date: 2023/4/12 20:20
 * 给你两个字符串：ransomNote 和 magazine ，判断 ransomNote 能不能由 magazine 里面的字符构成。
 *
 * 如果可以，返回 true ；否则返回 false 。
 *
 * magazine 中的每个字符只能在 ransomNote 中使用一次。
 */
public class hxb7_383 {

    public static void main(String[] args) {
        String ransomNote = "a", magazine = "b";
        System.out.println(canConstruct(ransomNote, magazine));
    }

//    自己写的，效率一般
    public static boolean canConstruct1(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) return false;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < magazine.length(); i++){
            char c = magazine.charAt(i);
            if (map.containsKey(c)){
                map.put(c, map.get(c) + 1);
            }else {
                map.put(c, 1);
            }
        }
        System.out.println(map);
        for (int i = 0; i < ransomNote.length(); i++){
            char c = ransomNote.charAt(i);
            if (!map.containsKey(c)) return false;
            else {
                map.put(c, map.get(c) - 1);
                if (map.get(c) < 0) return false;
            }
        }
        System.out.println(map);
        return true;
    }

    public static boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) return false;
        int[] hash = new int[26];
        for (int i = 0; i < magazine.length(); i++) hash[magazine.charAt(i)-'a']++;
        for (int i = 0; i < ransomNote.length(); i++) hash[ransomNote.charAt(i)-'a']--;
        for (int i = 0; i < 26; i++){
            if (hash[i] < 0) return false;
        }
        return true;
    }
}
